import { tt as constants } from '@/utils/business/constants.js'
import { getTime } from "@/api/business/ticket.js"
import { getTaskPlanInfo, logCollectStatus } from '@/api/business/inspect.js'
import { getNetwork } from '@/utils/device.js'
import { notice, utilities, business } from '@/utils/common.js'
import * as sqliteUtil from '@/utils/sqlite.js'
import * as sqliteInspect from '@/utils/business/inspectSqlite.js'
import project from '@/utils/config/project.js'

const tt = {
	/**
	 * 设置页面标题
	 * @param {*} typeName，类型
	 * @param {*} type:新增-，修改-，查看-，流程-
	 */
	setTitle(typeName, type) {
		let title = type + typeName;
		uni.setNavigationBarTitle({
			title: title,
		});
	},
	
	/**
	 * 获取系统时间(YYYY-MM-DD HH:mm:ss)
	 * 若无法获取,则使用浏览器时间
	 */
	async getSystemTime(){
		let result = await getTime()
		return result.result ? result.result.result : utilities.getNowDateTime()
	},
	
	/**
	 * 处理附加文档附件
	 * @param {*} files：当前附件
	 * @param {*} delFiles：已删除附件
	 * @param {*} isMain：主附类型:0-附票 1-主票 2-操作票
	 * @param {*} ttId：工作票号/附票号/操作票号
	 */
	handleAttachFiles(files, delFiles, isMain, ttId) {
		// 已删除附件设置flag
		delFiles.forEach(item => {
			item.flag = 'del'
		})
		// 数组合并
		files.push.apply(files, delFiles)
		
		let attachFileList = []
		// 根据类型分组
		let groupList = this.handleAttachFilesGroup(files)
		groupList.forEach(item => {
			let ttAttachFile = {}
			ttAttachFile.isMain = isMain
			ttAttachFile.ttId = ttId
			
			let attachTag = ''
			let fileList = []
			let fileNameList = []
			item.attachType.forEach(i => {
				attachTag = i.attachType
				if(i.flag != 'del') {
					fileNameList.push(i.name)
					fileList.push(i)
				}
			})
			ttAttachFile.attachTag = attachTag
			ttAttachFile.attachFiles = JSON.stringify(fileList)
			ttAttachFile.attachFileNames = fileNameList.join(",")
			attachFileList.push(ttAttachFile)
		})
		return attachFileList
	},
	
	/**
	 * 按照类型分组
	 */
	handleAttachFilesGroup(dataList, name = 'attachType') {
		let list = [] // 定义空数据用于存放同类type数据
		let obj = {} // 定义空对象用于获取同类type数据
		
		if (dataList.length > 0) {
			for (let item of dataList) {
				if (obj['group_' + item.attachType]) {
					obj['group_' + item.attachType].push(item)
				} else {
					obj['group_' + item.attachType] = [item]
				}
			}
			for (let key in obj) {
				list.push({
					[name]: obj[key]
				})
			}
		}
		return list
	}
}

const inspect = {
	/**
	 * 验证管控模式
	 * @param taskId 	任务ID
	 * @param code   	码值
	 * @param type   	类型(scan：扫描【扫码或物联设备】，hand：手工输入)
	 * @param netWork   网络(online：在线，offline：离线)
	 */
	async verifyControlMode(taskId, code, type, netWork) {
		let taskInfo, isAreaLocation, isScanHand, inspectionList;
		if(netWork == 'online') {
			// 巡检任务信息
			taskInfo = await getTaskPlanInfo(taskId)
			// 区域设备
			isAreaLocation = taskInfo.data.isAreaLocation
			// 管控模式
			isScanHand = taskInfo.data.isScanHand
			// 检查项信息
			inspectionList = taskInfo.data.taskInspectionList
		} else if(netWork == 'offline') {
			// 巡检任务信息
			let task = await sqliteUtil.selectTableInfo('m_ri_task', 'task_id', taskId)
			utilities.formatHumpLineTransfer(task)
			taskInfo = task[0]
			// 区域设备
			isAreaLocation = taskInfo.isAreaLocation
			// 管控模式
			isScanHand = taskInfo.isScanHand
			// 检查项信息
			let inspection = await sqliteUtil.selectTableInfo('m_ri_task_inspection', 'task_id', taskId)
			utilities.formatHumpLineTransfer(inspection)
			inspectionList = inspection
		}
		
		let scanNo, scanType;
		if(type == 'scan') {
			let data = business.handleCode(code)
			scanType = data.scanType
			scanNo = data.scanNo
		} else if(type == 'hand') {
			scanNo = code
			scanType = isAreaLocation == 1 ? 'IDPOS' : 'KKS'
		}
		
		// 错误提示信息
		let msg = scanType == 'IDPOS' ? '区域不存在，请确认' : scanType == 'KKS' ? '设备位置不存在，请确认' : '查询失败，请确认'
		let flag = false
		let areaId, locaId;
		for(const item of inspectionList) {
			if(scanType == 'IDPOS' && item.areaNo == scanNo) {
				areaId = item.areaId
				locaId = item.locaId
				flag = true
			} else if(scanType == 'KKS' && item.locaNo == scanNo) {
				areaId = item.areaId
				locaId = item.locaId
				flag = true
			}
		}
		
		let result = {
			isPass: flag,
			areaId: areaId,
			locaId: locaId,
			msg: msg
		}
		return result
	},
	// 记录设备采集状况
	logCollectStatus(params) {
		params.linkType = 1
		params.serialNo = uni.getStorageSync("serialNo")
		params.createTime = utilities.getNowDateTime()
		
		if(project.LOG_COLLECT) {
			if(getNetwork()) { // 在线
				params.reportUser = uni.getStorageSync("userId")
				params.reportUserName = uni.getStorageSync("userName")
				params.companyId = uni.getStorageSync("companyId")
				params.createUser = uni.getStorageSync("userId")
				
				logCollectStatus(params)
			} else { // 离线
				sqliteInspect.insertMCpisAppCollectStatus(params)
			}
		}
	}
}

const wo = {
	/**
	 * 数组排序
	 * @param arr 		 被处理的数组
	 * @param sort_key1  排序字段(首要排序字段)
	 * @param sort_key2  排序字段(备用排序字段)
	 */
	formatDataSort(arr, sort_key1, sort_key2) {
		const dataSort = (list, sort_key1, sort_key2) => {
			list = list.sort(function(a, b) {
				if(a[sort_key1]) {
					let v1 = a[sort_key1].split('.')
					let v2 = b[sort_key1].split('.')
					const minVersionLens = Math.min(v1.length, v2.length)
					let result = 0
					for (let i = 0; i < minVersionLens; i++) {
						const curV1 = Number(v1[i])
						const curV2 = Number(v2[i])
						
						if (curV1 > curV2) {
							result = 1
							return 1
							break;
						} else if (curV1 < curV2) {
							result = -1
							return -1
							break;
						}
					}
					if (result === 0 && (v1.length !== v2.length)) {
						const v1BiggerThenv2 = v1.length > v2.length;
						const maxLensVersion = v1BiggerThenv2 ? v1 : v2;
						for (let i = minVersionLens; i < maxLensVersion.length; i++) {
							const curVersion = Number(maxLensVersion[i])
							if (curVersion > 0) {
								if(v1BiggerThenv2) {
									return 1
								} else {
									return -1
								}
								break;
							}
						}
					}
				} else {
					return a[sort_key2] - b[sort_key2]
				}
			})
			return list
		}
		arr = dataSort(arr, sort_key1, sort_key2)
		return arr
	},
	/**
	 * 数组分组（多字段）
	 * @param arr  		  被处理的数组
	 * @param group_key1  分组字段1
	 * @param group_key2  分组字段2
	*/
	formatDataGroup(arr, group_key1, group_key2) {
		var map = [{
			[group_key1]: arr[0][group_key1],
			[group_key2]: arr[0][group_key2],
			item: [arr[0]],
		}]
		for (var i = 1; i < arr.length; i++) {
			let bool = map.some((it)=>{
				if((arr[i][group_key1] == it[group_key1]) && (arr[i][group_key2] == it[group_key2])){
					it['item'].push(arr[i])
				}
				return ((arr[i][group_key1] == it[group_key1]) && (arr[i][group_key2] == it[group_key2]))
			})
			if(!bool){
				map.push({
					[group_key1]: arr[i][group_key1],
					[group_key2]: arr[i][group_key2],
					item: [arr[i]],
				})
			}
		}
		return map
	},
	/**
	 * 数组分组（单字段）
	 * @param arr  		 被处理的数组
	 * @param group_key  分组字段
	*/
	formatDataGroupSingle(arr, group_key) {
		const dataGroup = (list, f) => {
			const groups = {}
			list.forEach(function(o) { 
				const group = JSON.stringify(f(o));
				groups[group] = groups[group] || [];
				groups[group].push(o);
			})
			return Object.keys(groups).map(function (group) {
				return groups[group];
			})
		}
		arr = dataGroup(arr, function(item) {
			return [item[group_key]]
		})
		return arr
	}
}

export {
	tt,
	inspect,
	wo
}